package com.te;

import android.util.Log;
import org.jbox2d.collision.CircleDef;
import org.jbox2d.collision.PolygonDef;
import org.jbox2d.collision.ShapeDef;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;

public class BodyUtil {

    private final static String TAG = BodyUtil.class.getSimpleName();

    static Body createBody(World world, float x, float y, ShapeDef shapeDef, boolean setMassFromShapes, Object bodyUserData) {
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(x, y);
        Body body = world.createBody(bodyDef);
        body.createShape(shapeDef);
        if (setMassFromShapes) {
            body.setMassFromShapes();
            body.getShapeList().setUserData(bodyUserData);
        }
        Log.d(TAG, "added body at x,y " + x + " : " + y);

        
        return body;
    }

    static void createBorders(World world, int color, float width, float left, float top, float right, float bottom) {

        float bHeight = (bottom - top) / 2;
        float bWidth = (right-left) /2;
             
        // topLeft to topRight
        BodyUserData bodyUserData = new BodyUserData(color, null);
        PolygonDef polygonDef = new PolygonDef();
        polygonDef.setAsBox(bWidth, width);
        createBody(world, left+bWidth, top+width, polygonDef, false, bodyUserData);
       
        // topLeft to bottomLeft
        BodyUserData bodyUserData2 = new BodyUserData(color, null);
        polygonDef = new PolygonDef();
        polygonDef.setAsBox(width, bHeight);
        createBody(world, left+width, top+bHeight, polygonDef, false, bodyUserData2);

        // topRight to bottomRight
        BodyUserData bodyUserData3 = new BodyUserData(color, null);
        polygonDef = new PolygonDef();
        polygonDef.setAsBox(width, bHeight);
        createBody(world, right-width, top+bHeight, polygonDef, false, bodyUserData3);

        // bottomLeft to bottomRight
        BodyUserData bodyUserData4 = new BodyUserData(color + 2, null);
        polygonDef = new PolygonDef();
        polygonDef.setAsBox(bWidth, width);
        createBody(world, left+bWidth, bottom-width, polygonDef, false, bodyUserData4);

    }
    
    public static void createBall(World world, float x, float y, float radius) {
        
        // Create Shape with Properties
        CircleDef circleDef = new CircleDef();
        circleDef.radius = radius;
        circleDef.density = 1.9f;
        //0 = zero friction, 1 = a lot.
        circleDef.friction = 0.1f;
        //0 = zero bounce, 1 = perfect reflection
        circleDef.restitution = 0.8f;


        createBody(world, x, y, circleDef, true, 0f);

    }
    
    

    static int scaleToAndroidPixelCoord(float coord) {
        return (int) (30 * coord);
    }
    
    static float scaleFromAndroidPixelCoord(float coord) {
        return (coord / 30);
    }

}
